/*
 * Copyright ThinkTank Maths Limited 2006 - 2008
 *
 * This file is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This file is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this file. If not, see <http://www.gnu.org/licenses/>.
 */
package com.openlapi;

import java.io.IOException;

import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import thinktank.j2me.TTUtils;
import thinktank.j2me.TTUtils.ILogger;

/**
 * Standalone MIDlet that prints locations to the screen.
 * 
 * @author Samuel Halliday, ThinkTank Maths Limited
 */
public class LocationDisplayer extends MIDlet {
	private final Form form;

	private volatile LocationProvider provider;

	/**
	 * @throws LocationException
	 * @throws IOException
	 */
	public LocationDisplayer() throws LocationException {
		form = new Form("OpenLAPI Location Displayer");
		TTUtils.registerLogger(new ILogger() {
			public void log(String message) {
				form.append(message);
				Display.getDisplay(LocationDisplayer.this).setCurrent(form);
			}
		});
		provider = LocationProvider.getInstance(null);
	}

	protected void destroyApp(boolean force) throws MIDletStateChangeException {
		provider.setLocationListener(null, -1, -1, -1);
	}

	protected void pauseApp() {
		provider.setLocationListener(null, -1, -1, -1);
	}

	protected void startApp() throws MIDletStateChangeException {
		provider.setLocationListener(new LocationListener() {
			public void locationUpdated(LocationProvider provider,
					Location location) {
				String msg;
				if (!location.isValid()) {
					msg = "invalid location";
				} else {
					QualifiedCoordinates qc =
							location.getQualifiedCoordinates();
					String longitude =
							Coordinates.convert(qc.getLongitude(),
								Coordinates.DD_MM);
					String latitude =
							Coordinates.convert(qc.getLatitude(),
								Coordinates.DD_MM);
					msg = "valid location: " + longitude + ", " + latitude;
				}
				String info =
						location.getExtraInfo("application/X-jsr179-location-nmea");
				form.append(msg);
				if (info != null)
					form.append(" " + info);

				Display.getDisplay(LocationDisplayer.this).setCurrent(form);
			}

			public void providerStateChanged(LocationProvider provider,
					int newState) {
			}
		}, 10, 5, 5);
	}

}
